<template>
  <div>
    <table
      border="1"
      width="700"
      style="border-collapse: collapse"
    >
      <caption>
        购物车
      </caption>
      <thead>
        <tr>
          <th>
            <input type="checkbox" v-model="chkAll" /> <span>全选</span>
          </th>
          <th>名称</th>
          <th>价格</th>
          <th>数量</th>
          <th>总价</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <!-- 组件 -->
        <tr-com v-for="(item, index) in goodList" :key="index" :tr="item" :index="index" @doing="doing"></tr-com>
      </tbody>
      <tfoot>
        <tr>
          <td>合计:</td>
          <td colspan="5">
              {{total}}
          </td>
        </tr>
      </tfoot>
    </table>
  </div>
</template>

<script>
// 把一行tr封装成一个组件, 然后v-for循环复用传值
import TrCom from './components/tr-com'
export default {
  data () {
    return {
      goodList: [
        {
          name: '诸葛亮',
          price: 1000,
          num: 1,
          checked: false
        },
        {
          name: '蔡文姬',
          price: 1500,
          num: 1,
          checked: false
        },
        {
          name: '妲己',
          price: 2000,
          num: 1,
          checked: false
        },
        {
          name: '鲁班',
          price: 2200,
          num: 1,
          checked: false
        }
      ]
    }
  },
  // 注册组件
  components: {
    TrCom
  },
  // 方法
  methods: {
    // 自定义方法
    doing (type, i) {
      type === 'chk' && (this.goodList[i].checked = !this.goodList[i].checked) // 选中
      type === 'add' && this.goodList[i].num++ // 增减
      type === 'sub' && this.goodList[i].num > 1 && this.goodList[i].num--
      type === 'del' && this.goodList.splice(i, 1) // 删除
    }
  },
  // 计算属性
  computed: {
    // 全选全不选
    chkAll: {
      get () {
        return this.goodList.every(el => el.checked)
      },
      set (val) {
        this.goodList.map(el => (el.checked = val))
      }
    },
    // 合计
    total () {
      return this.goodList.filter(el => el.checked).reduce((p, n) => p + (n.price * n.num), 0).toFixed(2)
    }
  }
}
</script>

<style>
</style>
